import React, { useState } from 'react';
import { Form, Button, Radio, Input, Popconfirm, Space, Tag, message } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import IconFont from '@/components/IconFont/index.jsx';
import SelectTagModal from '@/pages/OrderModule/common/bizcomponents/SelectTagModal';
import SetExpressModal from '../../../SetExpressModal';
import SetOrderStatusForErrorModal from '../../../SetOrderStatusForErrorModal';
import VoidOrderModal from '../../../VoidOrderModal';
import Api from '../../../../utils/service.js';
import ActionApi from '../../../../service.js';
import { inputLogisticsNoAndSendOp, updateRemarkInfo } from '../../service.js';
import Style from '../../index.module.less';
import { labelIconMap, labelNameMap } from "@/utils/config";

const rules = [{required: true, message: '请输入运单号'},{pattern: /^[^\u4e00-\u9fa5]{5,20}$/, message:'运单号格式不对，限5-20位'}];
export default ({ initValues = {}, orderList, item = {}, handleOk }) => {

  const [form] = Form.useForm();

  const [spinning, setSpinning] = useState(false);
  const [visible, setVisible] = useState(false);
  const [type, setType] = useState(1);

  const [currentTagList, setCurrentTagList] = useState(initValues?.labelIds || [])

  const onFinish = async (val) => {
    const { type } = val;
    setSpinning(true);
    const { msg, success } = await inputLogisticsNoAndSendOp({ 
        type,
        orderId: item.id,
        logisticsNo: type ? (type == 1 ? val['input-number1'] : val['input-number3']): undefined
     });
    setSpinning(false);
    if (success) {
      message.success(msg);
      handleOk();
    }
  }

  //审核订单
  const handleAuditOrder = async () => {
    setSpinning(true);
    const { msg, success } = await Api.vertifyOrder({ orderIds: [item.id] });
    setSpinning(false);
    if (success) {
      message.success(msg);
      handleOk();
    }
  }

  //取消作废
  const handleCancelOrder = async () => {
    setSpinning(true);
    const { msg, success } = await Api.cancelVoidOrder([item.id]);
    setSpinning(false);
    if (success) {
      message.success(msg);
      handleOk();
    }
  }

  //复制订单
  const handleCopyOrder = async () => {
    setSpinning(true);
    const { msg, success } = await ActionApi.copyOrderOp({orderId: item.id});
    setSpinning(false);
    if (success) {
      message.success('复制成功，新生成审核订单');
      handleOk(true);
    }
  }

  //获取运单号
  const handleGetBill = async () => {
    setSpinning(true);
    const { msg, success } = await ActionApi.getLogisticsNoOp([item.id]);
    setSpinning(false);
    if (success) {
      message.success(msg);
      handleOk();
    }
  }

  const handleSave = async () => {
    form.validateFields().then(res=>{
      console.log(form.getFieldsValue())
    })
  }

  const iconMaps = {
    'auditOrder': <IconFont type={'iconaudioOrder'}></IconFont>,
    'setExpress': <IconFont type={'iconsetExpress'}></IconFont>,
    'flagError': <IconFont type={'iconsignError'}></IconFont>,
    'copyOrder': <IconFont type={'iconcopyOrder'} style={{fontSize:'17px', position:'relative', left: '-2px'}}></IconFont>,
    'zuofei': <IconFont type={'iconvoidOrder'}></IconFont>,
    'getBill': <IconFont type={'icongetBill'}></IconFont>,
    'cancel': <IconFont type={'iconorder-time'} style={{fontSize:'17px', position:'relative', left: '-2px'}}></IconFont>,
  },
    btnMaps = {
      'auditOrder': (<Popconfirm title='确定审核该订单？' onConfirm={handleAuditOrder}>
        <div className={Style['anchor-item']}>
          <div className={Style['anchor-icon']}>{iconMaps['auditOrder']}</div>
          审核订单
        </div>
      </Popconfirm>),
      'setExpress': (<div className={Style['anchor-item']} onClick={() => setVisible('setExpress')}>
        <div className={Style['anchor-icon']}>{iconMaps['setExpress']}</div>
        设快递
      </div>),
      'setError': (<div className={Style['anchor-item']} onClick={() => setVisible('setError')}>
        <div className={Style['anchor-icon']}>{iconMaps['flagError']}</div>
        标异常
      </div>),
      'copyOrder': (<Popconfirm title='确定复制该订单？' onConfirm={handleCopyOrder}>
        <div className={Style['anchor-item']}>
          <div className={Style['anchor-icon']}>{iconMaps['copyOrder']}</div>
          复制订单
        </div>
      </Popconfirm>),
      'setVoid': (<div className={Style['anchor-item']} onClick={() => setVisible('setVoid')}>
        <div className={Style['anchor-icon']}>{iconMaps['zuofei']}</div>
        作废订单
      </div>),
      'getBill': (<Popconfirm title='确定获取运单号？' onConfirm={handleGetBill}>
        <div className={Style['anchor-item']}>
          <div className={Style['anchor-icon']}>{iconMaps['getBill']}</div>
          获取运单号
        </div>
      </Popconfirm>),
      'cancel': (<Popconfirm title='确定取消作废？' onConfirm={handleCancelOrder}>
        <div className={Style['anchor-item']}>
          <div className={Style['anchor-icon']}>{iconMaps['cancel']}</div>
          取消作废
        </div>
      </Popconfirm>)
    },
    stateHasBtnMaps = {
      10: ['auditOrder', 'setExpress', 'setError', 'copyOrder', 'setVoid', 'getBill'],
      20: ['setError', 'copyOrder', 'setVoid', 'getBill'],
      30: ['setExpress', 'setError', 'copyOrder', 'setVoid', 'getBill'],
      40: ['copyOrder'],
      50: ['cancel', 'copyOrder'],
    };

  //弹框参数
  const ModalProps = {
    orderList,
    id: item.id,
    singleIdForArray: [item.id],
    handleOk() {
      setVisible(false);
      handleOk();
    },
    handleCancel() {
      setVisible(false);
    }
  };

  //修改标签
  const handleChangeTag = async (data) => {
    setSpinning(true);
    const { flag, buyerMessage, sellerMessage, orderRemark } = item;
    const { msg, success} = await updateRemarkInfo({
      buyerMessage, 
      orderRemark,
      flag: flag[0],
      sellerRemark: sellerMessage,
      id: item.id,
      updateLabelFlag: true,
      labelIds: data.map(item => item.labelId)
    });
    setSpinning(false);
    if(success){
      message.success(msg || '操作成功');
      setCurrentTagList(data);
      handleOk();
    }
  }

  return (<>
    {visible == 'setExpress' && <SetExpressModal {...ModalProps} />}
    {visible == 'setError' && <SetOrderStatusForErrorModal {...ModalProps} />}
    {visible == 'setVoid' && <VoidOrderModal {...ModalProps} />}
    <div className={Style['operator_box_item']}>
    {
      stateHasBtnMaps[item.state]?.map(item => <span key={item}>{btnMaps[item]}</span>)
    }
    </div>
   
    {
      [10, 20, 30].includes(item.state) && (<div className={Style['operator_box_item']} style={{paddingLeft:'6px'}}><Form
        form={form}
        onFinish={onFinish}
        initialValues={{ "type": 1 }}
        autoComplete='off'
      >
        <Form.Item
          name="type"
          label=""
          rules={[
            {
              required: true,
              message: 'Please pick an item!',
            },
          ]}
        >
          <Radio.Group onChange={e=>setType(e.target.value)} value={type}>
            <div>
              <Radio value={1} style={{fontSize:'12px'}}>输入运单号</Radio>
              <Form.Item name="input-number1" style={{ margin: "0 0 0px 6px" }} rules={type == 1 ? rules : []}>
                <Input size='small' />
              </Form.Item>
            </div>

            {
              item.state == 20 && (<>
                <div>
                  <Radio value={2} style={{fontSize:'12px', wordBreak:'break-word'}}>获取运单号，直接发货</Radio>
                </div>

                <div>
                  <Radio value={3} style={{fontSize:'12px', wordBreak:'break-all'}}>输入快递单号，直接发货</Radio>
                  <Form.Item name="input-number3" style={{ margin: "0 0 0 6px" }} rules={type == 3 ? rules : []}>
                    <Input size='small' />
                  </Form.Item>
                </div>
              </>)
            }

          </Radio.Group>
        </Form.Item>
        <Form.Item name="input-number3" style={{ textAlign: "right", marginRight: "12px", marginBottom: 0 }}>
          <Button htmlType="submit" type='primary'>保存</Button>
        </Form.Item>
      </Form></div>)
    }

    <div className={Style['operator_box_item']} style={{paddingLeft:'6px'}}>
      <h4 style={{marginBottom:'4px'}}>订单标签</h4>
      <Space wrap>
        {currentTagList.map(item => {
          return (labelNameMap[item.labelId] ? (
            <span key={item.labelId} style={{ fontSize: 20 }}>
              <IconFont type={labelIconMap[item.labelId]} />
            </span>
          ) : (
            <Tag key={item.labelId} color="#B1B7C3">
              {item.labelName}
            </Tag>
          ))
        })}
      </Space>
      <SelectTagModal defaultValue={currentTagList.map(item => item.labelId)} onChange={handleChangeTag}>
        <Button type="link" style={{marginTop:'4px'}}>
          <IconFont type="icona-lujing1" />
          添加标签
        </Button>
      </SelectTagModal>
    </div>
    <CommonLoading loading={spinning} />
  </>)
}